<template>
  <div class="container">
    <div class="activite-box">
      <div class="activite-subject">
        <p style="text-align: center; margin: 2vw auto">
          {{ activityData.subject }}
        </p>
        <!-- <el-button type="primary" round class="activite-button" @click="goActivitieDetails(activityData)">查看详情</el-button> -->
      </div>
      <p v-show="activityData.club" class="fsz26 activite-club">
        {{ activityData.club }}
      </p>
      <p class="fsz26 activite-type">{{ activityData.activityType }}</p>
      <p class="signUpStartTitle" v-if="activityData.isCountDown">距离报名开始</p>
      <div class="countdown">
        <CountDown :stopTime="stopTime" v-show="stopTime" class="countdown" v-if="activityData.isCountDown"></CountDown>
      </div>
      <div class="activitie-button-box">
        <el-button class="activitie-button" v-if="activityData.isCountDown">活动{{ activityData.statusName
        }}</el-button>
        <div v-show="activityData.joinStatus === 0">
          <el-button class="activitie-button">名额已满</el-button>
          <p style="font-size: 0.52vw">非常抱歉，名额不足，欢迎下次再来</p>
        </div>
        <div v-show="activityData.joinStatus === 2">
          <el-button class="activitie-button" @click="handleOtherAction(activityData.id)">
            提交报名信息
          </el-button>
          <p style="font-size: 0.52vw">
            您已抢到名额，15分钟内有效，请尽快提交报名信息
          </p>
        </div>
        <div v-show="activityData.joinStatus === 3">
          <el-button class="activitie-button">排队中</el-button>
          <p style="font-size: 0.52vw">活动热门请等待</p>
        </div>
        <div v-show="activityData.joinStatus === 4">
          <el-button class="activitie-button" @click="tosee(activityData.id)">查看报名</el-button>
          <p style="font-size: 0.52vw">您已报名成功</p>
        </div>
        <div v-show="activityData.joinStatus === 5">
          <el-button @click="openDialog(activityData.id)">抢名额</el-button>
        </div>
        <div v-show="activityData.joinStatus === -1">
          <el-button class="activitie-button" @click="eventEnded">报名已结束</el-button>
        </div>
        <div v-show="activityData.joinStatus === -2">
          <el-button class="activitie-button" @click="eventEnded">活动已结束</el-button>
        </div>
      </div>
      <p class="fsz26">
        活动时间：{{ activityData.activityStart }} -
        {{ activityData.activityEnd }}
      </p>
      <p class="fsz26">
        报名时间：{{ activityData.joinStart }} - {{ activityData.joinEnd }}
      </p>
      <p class="fsz26">活动地址：{{ activityData.address }}</p>
      <p class="fsz26">联系方式：{{ activityData.contactInfo }}</p>
      <p class="fsz26">活动人数：{{ activityData.alimit }}</p>
      <div class="flex fsz26">
        <p class="nowrap">活动规则：</p>
        <p>{{ activityData.rules }}</p>
      </div>
      <div class="flex fsz26">
        <p class="nowrap">评分标准：</p>
        <p>{{ activityData.evaluationCriteria }}</p>
      </div>
      <div class="flex fsz26">
        <p class="nowrap">奖项设置：</p>
        <p>{{ activityData.awardSettings }}</p>
      </div>
      <div class="flex fsz26">
        <p class="nowrap">参数对象要求：</p>
        <p>{{ activityData.participantRequirements }}</p>
      </div>


      <el-dialog :append-to-body="true" title="欢迎报名" :visible.sync="dialogVisible" width="30%"
        :before-close="handleClose" center>
        <el-form :model="activityInfo" :rules="rules" ref="activityInfo" label-width="100px" class="demo-ruleForm">
          <el-form-item label="姓名" prop="name" size="samll" class="inpbox">
            <el-input v-model="activityInfo.name"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone" v-model="activityInfo.phone" class="inpbox">
            <el-input v-model.number="activityInfo.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender" class="inpbox">
            <el-radio-group v-model="activityInfo.gender">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1" style="margin-left: 10px">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="所属院系" required style="margin-top: 5px">
            <el-col :span="11">
              <el-form-item prop="collegeId">
                <el-select filterable v-model="activityInfo.collegeId" placeholder="请选择学院"
                  @change="colleageChanged(activityInfo.collegeId)">
                  <el-option v-for="(item, index) in collegeAndMajor" :key="index" :label="item.collegeName"
                    :value="item.collegeId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col class="lines" :span="2" style="text-align: center">-</el-col>
            <el-col :span="11">
              <el-form-item prop="majorId">
                <el-select v-model="activityInfo.majorId" placeholder="请选择专业">
                  <el-option filterable v-for="(item, index) in majorList" :key="index" :label="item.name"
                    :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="班级" prop="sClass" size="samll" class="inpbox">
            <el-input v-model="activityInfo.sClass"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button id="elbox" type="primary" @click="submitForm('activityInfo')"
              v-loading.fullscreen.lock="fullscreenLoading">立即报名</el-button>
            <el-button id="resetForm" @click="resetForm('activityInfo')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { select } from "@/api/organizations/index.js";
import { getActivityLists } from "@/api/cms/cms.js";
import Cookies from "js-cookie";
import {Message} from "element-ui"
import {
  getQualifications,
  addJoinActivity,
  checkActivityStatus,
  getCurrentTime,
} from "../../api/activity";
import CryptoJS from "crypto-js";
//倒计时组件
import CountDown from "@/utils/countDown.vue";

export default {
  components: {
    CountDown,
  },
  asyncData({ query }) {
    // 返回一个对象，其中包含了从上下文(query)中获取的noticeId
    // 这个noticeId将被用作组件的一个属性，可以在组件的模板或方法中使用
    return {
      noticeId: query.id,
    };
  },
  data() {
    return {
      club: [],
      activityData: {},
      dialogVisible: false,
      currentTime: "",
      collegeAndMajor: [],
      majorList: [],
      activityInfo: {
        userId: "",
        sClass: "",
        activityId: "",
        name: "",
        alimit: 0, //活动人数限制
        gender: 0,
        phone: "",
        majorId: "",
        collegeId: "",
      },
      fullscreenLoading: false, //活动报名表单的控制加载
      rules: {
        name: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur",
          },
          {
            min: 2,
            max: 5,
            message: "长度在 2 到 5 个字符",
            trigger: "blur",
          },
        ],
        alimit: [
          {
            type: "number",
            min: 0,
            message: "数值不能小于0",
            trigger: "blur",
          },
        ],
        collegeId: [
          {
            required: true,
            message: "请选择学院",
            trigger: "blur",
          },
        ],
        majorId: [
          {
            required: true,
            message: "请选择专业",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号码格式不正确",
          },
        ],
        gender: [
          {
            required: true,
            message: "请选择性别",
            trigger: "blur",
          },
        ],
        sclass: [
          {
            required: true,
            message: "请输入班级",
            trigger: "blur",
          },
          {
            min: 3,
            message: "长度最少3字符",
            trigger: "blur",
          },
        ],
      },
      intervalId: null, // 用于存储定时器的 ID
      strIdReady: false,
      stopTime: "",
    };
  },
  async created() {
    await this.getClubsByPage();
    await this.getActivityList();
    this.startInterval();
    this.getUserId();
    this.getColInfo();
    this.stopTime = this.activityData.joinEnd;
  },

  beforeDestroy() {
    // 清除之前的定时器
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  },
  methods: {
    getClubsByPage(data) {
      return new Promise((resolve) => {
        select({
          pageNum: 1,
          pageSize: 999999,
          data,
        }).then((res) => {
          const { JoinClubsByPage } = res.data;
          this.club = JoinClubsByPage.records;
          resolve();
        });
      });
    },
    getActivityList() {
      return new Promise((resolve) => {
        getActivityLists(1, 1, { id: this.noticeId }).then((res) => {
          if (res.code == 20000) {
            this.activityData = res.data.list.records[0];
            const club = this.club.filter(
              (es) => es.id == this.activityData.clubId
            );
            this.activityData.club = club.length ? club[0].name : "";
          }
          resolve();
        });
      });
    },
    startInterval() {
      // 清除之前的定时器
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
      // 创建新的定时器
      this.intervalId = setInterval(() => {
        this.fetchData(this.activityData);
      }, 1000);
    },
    resetForm(activityInfo) {
      this.$refs[activityInfo].resetFields();
    },
    formattedDate(time) {
      const date = new Date(time);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    getCurrentTime() {
      return new Promise((resolve) => {
        getCurrentTime().then((res) => {
          if (res.code === 20000) {
            this.currentTime = res.data.date;
          }
          resolve(res.data.date);
        });
      });
    },
    async fetchData(activity) {
      await this.getCurrentTime();
      activity.isCountDown = false;
      if (
        new Date(this.currentTime).getTime() >
        new Date(activity.joinStart).getTime() &&
        new Date(this.currentTime).getTime() <
        new Date(activity.joinEnd).getTime()
      ) {
        //报名中
        checkActivityStatus(activity.id).then((res) => {
          if (res.code === 20000) {
            activity.joinStatus = res.data.status;
          }
        });
      } else if (
        new Date(this.currentTime).getTime() >
        new Date(activity.joinEnd).getTime() &&
        new Date(this.currentTime).getTime() <
        new Date(activity.activityStart).getTime()
      ) {
        activity.joinStatus = -1;
      } else if (activity.status === 3) {
        activity.joinStatus = -2;
      } else {
        //不可报名显示倒计时
        activity.isCountDown = true;
      }
      this.$forceUpdate();
    },
    eventEnded() {
      this.$message.warning(
        "报名已经结束，但请继续关注我们的后续活动，下次机会不要错过哦！"
      );
    },
    handleOtherAction(activityId) {
      this.dialogVisible = true; // 打开对话框
      this.activityInfo.activityId = activityId;
      const activity = this.activityData;
      if (activity) {
        activity.isDistinguish = !activity.isDistinguish; // 区分活动
      }
    },
    handleClose(done) {
      done();
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     done();
      //   })
      //   .catch(_ => { });
    },
    colleageChanged(value) {
      for (let i = 0; i < this.collegeAndMajor.length; i++) {
        if (this.collegeAndMajor[i].collegeId === value) {
          this.majorList = this.collegeAndMajor[i].majorList;
          this.activityInfo.majorId = "";
        }
      }
    },
    getColInfo() {
      this.$store
        .dispatch("queryCollege")
        .then(() => {
          this.collegeAndMajor = this.$store.state.collegeAndMajor;
          for (let i = 0; i < this.collegeAndMajor.length; i++) {
            if (
              this.collegeAndMajor[i].collegeId === this.activityInfo.collegeId
            ) {
              this.majorList = this.collegeAndMajor[i].majorList;
            }
          }
        })
        .catch((error) => {
          console.error("获取学院专业列表失败", error);
        });
    },
    tosee() {
      //查看报名
      this.$router.push(`/userInfoForm`);
      this.$message.success("请准时参与");

      // this.dialogVisible = true; // 打开对话框
    },
    getUserId() {
      //获取用户id
      this.$store.dispatch("queryUser").then(() => {
        this.userId = this.$store.state.userInfo.id;
        this.activityInfo.userId = this.userId;

        if (this.activityId !== null && this.userId !== null) {
          this.strIdReady = true;
          this.encryptMD5();
        }
        //console.log(this.$store.state.userInfo.id); // 这里应该能获取到数据
      });
    },

    encryptMD5() {
      this.strId = this.activityId + this.userId;
      this.encryptedStr = CryptoJS.MD5(this.strId).toString();
      // 在控制台输出加密后的字符串
    },
    getQualification() {
      getQualifications(this.activityId, this.encryptedStr).then((res) => {
        if (res.code === 20000 || res.code === 20001) {
          console.log("Success:", res.message); // 打印成功消息
        } else {
          this.$message.error(res.message || "获取资格信息失败");
        }
      });
    },
    openDialog(activityId) {
      //抢名额
      this.getUserId();
      this.activityId = activityId; //获取相对应的activityId
      this.activityInfo.activityId = activityId; //报名表单获取相对应的activityId
      this.encryptMD5();
      this.getQualification();
      this.strIdReady = true; // 设置md5ID准备好
      const activity = this.activityData;
      if (activity) {
        activity.isDistinguish = !activity.isDistinguish; // 区分活动
      }
      this.$message.success("已抢到报名资格，请尽快提交报名表，15分钟后失效");
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 检查alimit值是否大于15，如果大于则不发送请求
          if (this.activityInfo.alimit && this.activityInfo.alimit > 15) {
            this.$message.warning("alimit值已超过15，不再发送请求");
            return; // 终止方法执行
          }
          addJoinActivity(this.activityInfo).then((res) => {
            if (res.code === 20000) {
              this.activityInfo.alimit += 1;
              this.fullscreenLoading = true;
              setTimeout(() => {
                this.fullscreenLoading = false;
              }, 2000); // 提交后加载2秒再完成，避免因网络不好而频繁点击
              this.$message.success("报名成功！");
              this.$router.push("/");
            } else {
              this.$message.error(res.data.message);
            }
          });
        } else {
          this.$message.error("请检查是否输入正确的数据");
        }
      });
      this.dialogVisible = false; // 打开对话框
    },
  },
  beforeRouteEnter(to, from, next) {
    if (Cookies.get("token")) {
      next()
    } else {
      Message.error("请先登录")
      next('/login')
    }
  }
};
</script>

<style scoped>
p {
  margin: 0;
  padding: 0;
}

.container {
  width: 100%;
  height: 100%;
  padding: 30px 0;
  background-image: url("../../assets/img/活动详细背景图.png");
  background-size: cover;
  /* 背景图片覆盖整个盒子 */
  background-position: center;
  /* 背景图片居中 */
  background-repeat: no-repeat;
  /* 背景图片不重复 */
}

/* 基础重置 */
.activite-box {
  max-width: 1200px;
  margin: auto !important;
  padding: 30px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.08);
  font-family: "Segoe UI", system-ui, sans-serif;
}

/* 标题样式 */
.activite-subject p {
  font-size: 2rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 20px 0;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f2f5;
  text-align: center;
  position: relative;
}

.activite-subject p::after {
  content: "";
  position: absolute;
  bottom: -2px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #409eff, #67c23a);
}

/* 信息项样式 */
.fsz26 {
  font-size: 1rem;
  color: #5e6d82;
  line-height: 1.7;
  margin: 15px 0;
  padding: 12px 20px;
  background: #f8fafc;
  border-radius: 8px;
  transition: all 0.3s;
}

.fsz26:hover {
  background: #f0f7ff;
  transform: translateX(5px);
}

/* 标签样式 */
.activite-club,
.activite-type {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 15px;
  font-size: 0.85rem;
  font-weight: 500;
  margin-right: 10px;
}

.activite-club {
  background: linear-gradient(135deg, #67c23a, #5aad36);
  color: #fff;
}

.activite-type {
  background: linear-gradient(135deg, #409eff, #3375b9);
  color: #fff;
}

.signUpStartTitle {
  font-size: 40px;
  margin: 10px auto;
  display: flex;
  justify-content: center;
}

.competitionStartTitle {
  font-size: 16px;
  margin: 10px auto;
  display: flex;
  justify-content: center;
  color: #444444;
}

.countdown {
  display: flex;
  justify-content: center;
}

/* 按钮容器 */
.activitie-button-box {
  /* margin: 40px 0; */
  padding: 20px;
  /* background: #f9fafb; */
  border-radius: 10px;
  text-align: center;
}

/* 状态按钮 */
.activitie-button {
  min-width: 160px;
  padding: 12px 30px;
  border-radius: 25px;
  font-size: 1rem;
  font-weight: 500;
  transition: all 0.3s;
  border: none;
  background: linear-gradient(135deg, #409eff, #3375b9);
  color: #fff;
  box-shadow: 0 4px 15px rgba(64, 158, 255, 0.3);
}

.activitie-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
}

/* 不同状态样式 */
.el-button[disabled] {
  background: #e0e0e0 !important;
  cursor: not-allowed;
}

/* 提示文字 */
.activitie-button-box p {
  font-size: 0.9rem;
  color: #8798a7;
  margin-top: 10px;
}

/* 表单对话框优化 */
::v-deep .el-dialog {
  border-radius: 12px !important;
}

::v-deep .el-dialog__header {
  border-bottom: 1px solid #f0f2f5;
}

::v-deep .el-dialog__title {
  font-weight: 600;
  color: #2c3e50;
}

::v-deep .el-form-item__label {
  font-weight: 500;
  color: #5e6d82;
}

::v-deep .el-input__inner {
  border-radius: 8px;
  transition: all 0.3s;
}

::v-deep .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .activite-box {
    padding: 20px;
    margin: 10px !important;
  }

  .activite-subject p {
    font-size: 1.5rem;
  }

  .fsz26 {
    padding: 10px;
    font-size: 0.9rem;
  }

  .activitie-button {
    min-width: 120px;
    padding: 10px 20px;
  }
}

/* 特殊状态样式 */
.activitie-button-box div[style*="font-size: 0.52vw"] p {
  font-size: 0.85rem !important;
  color: #ff6b6b;
  margin-top: 8px;
}

/* 学院专业选择器 */
.lines {
  color: #c0c4cc;
  font-weight: 300;
}

/* 加载动画 */
::v-deep .el-loading-spinner .circular {
  width: 42px;
  height: 42px;
  animation: loading-rotate 2s linear infinite;
}

@keyframes loading-rotate {
  100% {
    transform: rotate(360deg);
  }
}
</style>
